//SPDX-FileCopyrightText: Copyright 2022-2024 深圳市同心圆网络有限公司
//SPDX-License-Identifier: GPL-3.0-only

import React, { useState } from "react";
import { observer } from 'mobx-react';
import type { DepartMentOrMember } from "@/api/org";
import { change_org_owner } from "@/api/org";
import { Button, message, Modal, Space, Table, Tag } from "antd";
import { useStores } from "@/hooks";
import type { ColumnsType } from 'antd/lib/table';
import UserPhoto from "@/components/Portrait/UserPhoto";
import type { MemberInfo } from "@/api/org_mebmer";
import { remove_member, move_member } from "@/api/org_mebmer";
import { request } from "@/utils/request";
import { useHistory } from "react-router-dom";
import SelectDepartMentModal from "./SelectDepartMentModal";
import ChangeMemberPermModal from "./ChangeMemberPermModal";

export interface MemberListProps {
    parentDepartMentId: string;
    onSelect: (newItem: DepartMentOrMember) => void;
}

const MemberList = (props: MemberListProps) => {
    const history = useHistory();

    const userStore = useStores('userStore');
    const orgStore = useStores('orgStore');
    const appStore = useStores('appStore');

    const [removeMemberInfo, setRemoveMemberInfo] = useState<MemberInfo | null>(null);
    const [newOwnerInfo, setNewOwnerInfo] = useState<MemberInfo | null>(null);
    const [moveMemberInfo, setMoveMemberInfo] = useState<MemberInfo | null>(null);
    const [permMemberInfo, setPermMemberInfo] = useState<MemberInfo | null>(null);

    const checkSelectAble = (myMember: MemberInfo | undefined, targetMember: MemberInfo): boolean => {
        if (myMember == undefined) {
            return false
        }
        if (myMember.member_user_id == orgStore.curOrg?.owner_user_id) {
            return true;
        }
        if (myMember.depart_ment_id_path.length > targetMember.depart_ment_id_path.length) {
            return false;
        }
        for (const item of myMember.depart_ment_id_path.entries()) {
            if (item[1] != targetMember.depart_ment_id_path[item[0]]) {
                return false;
            }
        }
        return true;
    }


    const removeMember = async () => {
        if (removeMemberInfo == null) {
            return;
        }
        await request(remove_member({
            session_id: userStore.sessionId,
            org_id: orgStore.curOrgId,
            member_user_id: removeMemberInfo.member_user_id,
        }));
        await orgStore.onLeave(orgStore.curOrgId, removeMemberInfo.member_user_id, history);
        if (removeMemberInfo.parent_depart_ment_id != "") {
            await orgStore.onRemoveDepartMent(orgStore.curOrgId, removeMemberInfo.parent_depart_ment_id);
        }
        setRemoveMemberInfo(null);
        message.info("删除成功");
    };

    const moveMember = async (destDepartMentId: string) => {
        if (moveMemberInfo == null) {
            return;
        }
        await request(move_member({
            session_id: userStore.sessionId,
            org_id: orgStore.curOrgId,
            member_user_id: moveMemberInfo.member_user_id,
            parent_depart_ment_id: destDepartMentId
        }));
        await orgStore.onUpdateMember(orgStore.curOrgId, moveMemberInfo.member_user_id);
        if (moveMemberInfo.parent_depart_ment_id != "") {
            await orgStore.onUpdateDepartMent(orgStore.curOrgId, moveMemberInfo.parent_depart_ment_id);
        }
        if (destDepartMentId != "") {
            await orgStore.onUpdateDepartMent(orgStore.curOrgId, destDepartMentId);
        }
        setMoveMemberInfo(null);
        message.info("移动成功");
    }

    const changeOrgOwner = async () => {
        if (newOwnerInfo == null) {
            return;
        }
        await request(change_org_owner({
            session_id: userStore.sessionId,
            org_id: orgStore.curOrgId,
            target_member_user_id: newOwnerInfo.member_user_id,
        }));
        await orgStore.initLoadOrgList();
        setNewOwnerInfo(null);
        message.info("设置成功");
    };

    const columns: ColumnsType<MemberInfo> = [
        {
            title: "名称",
            width: 180,
            render: (_, row: MemberInfo) => (
                <Space size="small">
                    <UserPhoto logoUri={row.logo_uri} style={{ width: "16px", borderRadius: "10px" }} />
                    <Button type="link" onClick={e => {
                        e.stopPropagation();
                        e.preventDefault();
                        props.onSelect({
                            type: "member",
                            id: row.member_user_id,
                            value: row,
                        });
                    }} disabled={!(checkSelectAble(orgStore.selfMember, row))}
                        style={{ minWidth: 0, padding: "0px 0px" }}>
                        {row.display_name}
                    </Button>
                </Space>
            ),
        },
        {
            title: "权限",
            render: (_, row: MemberInfo) => (
                <Space style={{ flexWrap: "wrap" }}>
                    {row.member_perm_info.manage_depart_ment_perm && (
                        <Tag>部门管理</Tag>
                    )}
                    {row.member_perm_info.manage_evaluate_target && (
                        <Tag>评估指标管理</Tag>
                    )}
                    {row.member_perm_info.view_all_evaluate && (
                        <Tag>查看当前及下属部门成员互评</Tag>
                    )}
                    {row.member_perm_info.manage_depart_ment_evaluate && (
                        <Tag>当前部门成员互评管理</Tag>
                    )}
                </Space>
            ),
        },
        {
            title: "个人信息",
            width: 100,
            render: (_, row: MemberInfo) => (appStore.vendorCfg?.work_bench.enable_user_resume && row.has_resume) ? "有" : "无",
        },
        {
            title: "操作",
            width: 200,
            render: (_, row: MemberInfo) => (
                <Space>
                    {(userStore.userInfo.userId == orgStore.curOrg?.owner_user_id || orgStore.selfMember?.member_perm_info.manage_depart_ment_perm == true) && (
                        <Button type="link" style={{ minWidth: 0, padding: "0px 0px" }}
                            onClick={e => {
                                e.stopPropagation();
                                e.preventDefault();
                                setPermMemberInfo(row);
                            }}>
                            设置权限
                        </Button>
                    )}
                    {userStore.userInfo.userId == orgStore.curOrg?.owner_user_id && (
                        <Button type="link" style={{ minWidth: 0, padding: "0px 0px" }}
                            onClick={e => {
                                e.stopPropagation();
                                e.preventDefault();
                                setMoveMemberInfo(row);
                            }}>移动</Button>
                    )}

                    {userStore.userInfo.userId == orgStore.curOrg?.owner_user_id && row.member_user_id != orgStore.curOrg?.owner_user_id && (
                        <Button type="link"
                            style={{ minWidth: 0, padding: "0px 0px" }} danger
                            onClick={e => {
                                e.stopPropagation();
                                e.preventDefault();
                                setRemoveMemberInfo(row);
                            }}>删除</Button>
                    )}

                    {orgStore.curOrg?.owner_user_id == userStore.userInfo.userId && row.member_user_id != orgStore.curOrg?.owner_user_id && (
                        <Button type="link" style={{ minWidth: 0, padding: "0px 0px" }}
                            danger
                            onClick={e => {
                                e.stopPropagation();
                                e.preventDefault();
                                setNewOwnerInfo(row);
                            }}>
                            设为管理员
                        </Button>
                    )}
                </Space>
            ),
        }
    ];

    return (
        <>
            <Table rowKey="member_user_id" dataSource={orgStore.memberList.filter(item => item.parent_depart_ment_id == props.parentDepartMentId)}
                columns={columns} pagination={false} />

            {removeMemberInfo != null && (
                <Modal open title="删除成员" mask={false}
                    okText="删除" okButtonProps={{ danger: true }}
                    onCancel={e => {
                        e.stopPropagation();
                        e.preventDefault();
                        setRemoveMemberInfo(null);
                    }}
                    onOk={e => {
                        e.stopPropagation();
                        e.preventDefault();
                        removeMember();
                    }}>
                    是否删除成员&nbsp;{removeMemberInfo.display_name}&nbsp;?
                </Modal>
            )}

            {moveMemberInfo != null && (
                <SelectDepartMentModal skipDepartMentIdList={[moveMemberInfo.parent_depart_ment_id, orgStore.curOrg?.new_member_depart_ment_id ?? ""]}
                    onCancel={() => setMoveMemberInfo(null)}
                    onOk={departMentId => moveMember(departMentId)} />
            )}

            {newOwnerInfo != null && (
                <Modal open title="设为管理员" mask={false}
                    okText="设置" okButtonProps={{ danger: true }}
                    onCancel={e => {
                        e.stopPropagation();
                        e.preventDefault();
                        setNewOwnerInfo(null);
                    }}
                    onOk={e => {
                        e.stopPropagation();
                        e.preventDefault();
                        changeOrgOwner();
                    }}>
                    是否把成员&nbsp;{newOwnerInfo.display_name}&nbsp;设为管理员?
                    <p style={{ color: "red" }}>
                        您将失去管理员权限!!
                    </p>
                </Modal>
            )}

            {permMemberInfo != null && (
                <ChangeMemberPermModal memberInfo={permMemberInfo} onClose={() => setPermMemberInfo(null)} />
            )}
        </>
    );
};

export default observer(MemberList);